<?php

namespace app\api\controller;

use app\common\logic\Data;
use app\common\model\UserSetting;
use think\facade\Validate;
use think\facade\Db;
use app\lib\Result;

class Email extends Base
{
  /**
   * 邮件服务器列表
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://www.21ds.cn/
   */
  public function server_list()
  {
    $rule = [
      'pageNo'  => 'number',
      'pageSize'  => 'number',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    $where = [];

    if (!empty($data['title'])) {
      $where[] = ['title|_id', 'like', $data['title']];
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $dataList = Db::connect('mongodb')->name('email_server_list')->field('*')->where($where)->order('create_time', 'desc')->limit($limit, $data['pageSize'])->select()->toArray();
    $totalcount = Db::connect('mongodb')->name('email_server_list')->where($where)->count('id');

    foreach ($dataList as &$vo) {
      $vo['create_time'] = date('Y-m-d H:i:s', $vo['create_time']);
      $vo['is_ssl_bool'] = ($vo['is_ssl'] == 1) ? true : false;
      unset($vo['smtp_password']);
    }
    $returnData['data'] = $dataList;
    $returnData['totalCount'] = $totalcount;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public function all_server_list()
  {

    $dataList = Db::connect('mongodb')->name('email_server_list')->field('_id,title')->where('status', 1)->order('create_time', 'desc')->select()->toArray();
    return Result::Success($dataList);
  }
  public function all_tpl_list()
  {
    $dataList = Db::connect('mongodb')->name('email_tpl_list')->field('_id,title')->where('status', 1)->order('create_time', 'desc')->select()->toArray();
    return Result::Success($dataList);
  }
  public function tpl_list()
  {
    $rule = [
      'pageNo'  => 'number',
      'pageSize'  => 'number',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'cate_id' => input('param.cate_id', '', 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    $where = [];

    if (!empty($data['title'])) {
      $where[] = ['title|_id', 'like', $data['title']];
    }
    if (!empty($data['cate_id'])) {
      $where[] = ['cate_id', '=', $data['cate_id']];
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $dataList = Db::connect('mongodb')->name('email_tpl_list')->field('*')->where($where)->order('create_time', 'desc')->limit($limit, $data['pageSize'])->select()->toArray();
    $totalcount = Db::connect('mongodb')->name('email_tpl_list')->where($where)->count('id');

    $cateList = Db::connect('mongodb')->name('email_tpl_cate')->field('_id,title')->select()->toArray();
    $cateListArr = [];
    foreach ($cateList as &$vo) {
      $cateListArr[$vo['_id']] = $vo['title'];
    }

    foreach ($dataList as &$vo) {
      $vo['create_time'] = date('Y-m-d H:i:s', $vo['create_time']);
      $vo['cate_title'] = isset($cateListArr[$vo['cate_id']]) ? $cateListArr[$vo['cate_id']] : '';
    }
    $returnData['data'] = $dataList;
    $returnData['totalCount'] = $totalcount;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public function tpl_cate_list()
  {
    $rule = [
      'pageNo'  => 'number',
      'pageSize'  => 'number',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    $where = [];

    if (!empty($data['title'])) {
      $where[] = ['title|_id', 'like', $data['title']];
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $dataList = Db::connect('mongodb')->name('email_tpl_cate')->field('*')->where($where)->order('create_time', 'desc')->limit($limit, $data['pageSize'])->select()->toArray();
    $totalcount = Db::connect('mongodb')->name('email_tpl_cate')->where($where)->count('id');

    foreach ($dataList as &$vo) {
      $vo['create_time'] = date('Y-m-d H:i:s', $vo['create_time']);
    }
    $returnData['data'] = $dataList;
    $returnData['totalCount'] = $totalcount;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public function all_cate_list()
  {
    $selectResult = Db::connect('mongodb')->name('email_tpl_cate')->field('_id,title,pid,sort')->order('sort', 'desc')->select()->toArray();
    $sdata = new Data();
    foreach ($selectResult as &$vo) {
      $vo['title'] = $vo['title'];
      $vo['ids'] = join(',', $sdata->getArrSubIds($selectResult, $vo['_id'], '_id'));
    }
    $selectResult = $sdata->arr2table($selectResult, '_id');
    return Result::Success($selectResult);
  }
  public function send_log_list()
  {
    $rule = [
      'pageNo'  => 'number',
      'pageSize'  => 'number',
      'send_time_ranges|发送时间'  => 'require',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'es_id' => input('param.es_id', '', 'trim'),
      'send_time_ranges' => input('param.send_time_ranges/a', '', 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    // 构建查询条件
    $where = [];

    if (!empty($data['title'])) {
      $where[] = ['title|email|content', 'like', $data['title']];
    }
    if (!empty($data['es_id'])) {
      $where[] = ['es_id', '=', $data['es_id']];
    }
    $start_time = strtotime($data['send_time_ranges'][0]);
    $end_time = strtotime($data['send_time_ranges'][1]);
    if ($end_time - $start_time > 86400 * 90) {
      return Result::Error('时间跨度不能大于90天');
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $dataList = Db::connect('mongodb')->name('send_email_log')->field('*')->where($where)->whereBetweenTime('send_time', $start_time, $end_time)->order('send_time', 'desc')->limit($limit, $data['pageSize'])->select()->toArray();
    $totalcount = Db::connect('mongodb')->name('send_email_log')->where($where)->whereBetweenTime('send_time', $start_time, $end_time)->count('_id');

    foreach ($dataList as &$vo) {
      $vo['send_time'] = date('Y-m-d H:i:s', $vo['send_time']);
      $vo['read_time'] = (isset($vo['read_time']) && $vo['read_time'] > 0) ? date('Y-m-d H:i:s', $vo['read_time']) : '';
      $vo['email'] = substr($vo['email'], 0, 5) . '***' . substr($vo['email'], -7);
    }
    $returnData['data'] = $dataList;
    $returnData['totalCount'] = $totalcount;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public function send_setting()
  {
    if (request()->isPost()) {
      $rule = [
        'ip_limit|来路IP限制'  => 'number',
        'minute_limit|每分钟内发送上限'  => 'number',
        'hour_limit|每小时内发送上限'  => 'number',
        'day_limit|每个自然日内发送上限'  => 'number',
      ];
      $data = [
        'ip_limit' => input('param.ip_limit', '', 'trim'),
        'server_ip' => input('param.server_ip/a', '', 'trim'),
        'minute_limit' => input('param.minute_limit', '', 'trim'),
        'hour_limit' => input('param.hour_limit', '', 'trim'),
        'day_limit' => input('param.day_limit', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      $data['ip_limit'] = intval($data['ip_limit']);
      $data['minute_limit'] = intval($data['minute_limit']);
      $data['hour_limit'] = intval($data['hour_limit']);
      $data['day_limit'] = intval($data['day_limit']);
      $data['server_ip'] = (empty($data['server_ip'])) ? '' : implode(',', $data['server_ip']);
      $hasSetting = Db::connect('mongodb')->name('send_email_setting')->find();
      if (empty($hasSetting)) {
        unset($data['id']);
        $data['create_time'] = time();
        $data['uid'] = $this->uid;
        $data['username'] = $this->username;
        $data['_id'] = createId();
        Db::connect('mongodb')->name('send_email_setting')->insert($data);
      } else {
        $this->redis->del('dever:email:setting:' . $this->uid, 'full');
        Db::connect('mongodb')->name('send_email_setting')->update($data);
      }
      return Result::Success('', '设置成功');
    } else {
      $infoData = Db::connect('mongodb')->name('send_email_setting')->find();
      $infoData['server_ip'] = explode(',', $infoData['server_ip']);
      return json(['code' => 200, 'data' => $infoData, 'msg' => '获取成功']);
    }
  }
  /**
   * 编辑服务器信息
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://www.21ds.cn/
   */
  public function edit_server_info()
  {
    if (request()->isPost()) {
      $rule = [
        'title|备注'  => 'max:128',
        'smtp_server|SMTP服务器'  => 'require',
        'smtp_username|SMTP用户名'  => 'require',
        'status|状态'  => 'require',
        'is_ssl|是否启用SSL'  => 'require',
        'port|端口号'  => 'require|number',
        'sender|发件人'  => 'require',
        'server_secret|SecretKey'  => 'require',
      ];
      $data = [
        'id' => input('param._id', '', 'trim'),
        'smtp_server' => input('param.smtp_server', '', 'trim'),
        'smtp_username' => input('param.smtp_username', '', 'trim'),
        'title' => input('param.title', '', 'trim'),
        'smtp_password' => input('param.smtp_password', '', 'trim'),
        'status' => input('param.status', '', 'trim'),
        'is_ssl' => input('param.is_ssl', '', 'trim'),
        'port' => input('param.port', '', 'trim'),
        'sender' => input('param.sender', '', 'trim'),
        'sender_name' => input('param.sender_name', '', 'trim'),
        'reply_email' => input('param.reply_email', '', 'trim'),
        'server_secret' => input('param.server_secret', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      $limitCount = Db::connect('mongodb')->name('email_server_list')->count();
      $this->security::checkVersionLimit($this->user['version'], 'email_num', '邮件配置数量', $limitCount);
      $data['status'] = intval($data['status']);
      if (empty($data['smtp_password'])) {
        unset($data['smtp_password']);
      }
      $this->redis->del('dever:email:server:' . $data['id'], 'full');
      if (!empty($data['id'])) {
        $status = Db::connect('mongodb')->name('email_server_list')->where('_id', $data['id'])->update($data);
        $tag = '编辑';
      } else {
        if (!isset($data['smtp_password']) && empty($data['smtp_password'])) {
          return json(['code' => -1, 'data' => '', 'msg' => 'SMTP密码首次录入需设置']);
        }
        unset($data['id']);
        $data['create_time'] = time();
        $data['uid'] = $this->uid;
        $data['username'] = $this->username;
        $data['_id'] = createId('ES');
        $status = Db::connect('mongodb')->name('email_server_list')->insert($data);
        $tag = '新增';
      }
      if ($status > 0) {
        return json(['code' => 200, 'data' => '', 'msg' => $tag . '成功']);
      } else {
        return json(['code' => -1, 'data' => '', 'msg' => $tag . '失败，请重试']);
      }
    } else {
      $id = input('param.id', '', 'trim');
      if (!$id) {
        return json(['code' => 200, 'data' => [], 'msg' => 'success']);
      }
      $data = Db::connect('mongodb')->name('email_server_list')->where('_id', $id)->find();
      unset($data['smtp_password']);
      return json(['code' => 200, 'data' => $data, 'msg' => 'success']);
    }
  }
  public function edit_tpl_cate_info()
  {
    if (request()->isPost()) {
      $rule = [
        'title|标题'  => 'require|max:128',
        'status|状态'  => 'require',
        'pid|上级分类'  => 'require',
      ];
      $data = [
        'id' => input('param._id', '', 'trim'),
        'title' => input('param.title', '', 'trim'),
        'status' => input('param.status', '', 'trim'),
        'pid' => input('param.pid', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      $data['status'] = intval($data['status']);
      if (!empty($data['id'])) {
        $status = Db::connect('mongodb')->name('email_tpl_cate')->where('_id', $data['id'])->update($data);
        $tag = '编辑';
      } else {
        unset($data['id']);
        $data['create_time'] = time();
        $data['uid'] = $this->uid;
        $data['username'] = $this->username;
        $data['_id'] = createId('ETC');
        $status = Db::connect('mongodb')->name('email_tpl_cate')->insert($data);
        $tag = '新增';
      }
      if ($status > 0) {
        return json(['code' => 200, 'data' => '', 'msg' => $tag . '成功']);
      } else {
        return json(['code' => -1, 'data' => '', 'msg' => $tag . '失败，请重试']);
      }
    } else {
      $id = input('param.id', '', 'trim');
      if (!$id) {
        return json(['code' => 200, 'data' => [], 'msg' => 'success']);
      }
      $data = Db::connect('mongodb')->name('email_tpl_cate')->where('_id', $id)->find();
      unset($data['uid']);
      return json(['code' => 200, 'data' => $data, 'msg' => 'success']);
    }
  }
  public function edit_tpl_info()
  {
    if (request()->isPost()) {
      $rule = [
        'title|标题'  => 'require|max:128',
        'status|状态'  => 'require',
        'tpl|模板内容'  => 'require',
        'cate_id|模板分类'  => 'require',
      ];
      $data = [
        'id' => input('param._id', '', 'trim'),
        'title' => input('param.title', '', 'trim'),
        'status' => input('param.status', '', 'trim'),
        'tpl' => input('param.tpl', '', 'trim'),
        'cate_id' => input('param.cate_id', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      $data['status'] = intval($data['status']);
      $this->redis->del('dever:email:template:' . $data['id'], 'full');
      if (!empty($data['id'])) {
        $status = Db::connect('mongodb')->name('email_tpl_list')->where('_id', $data['id'])->update($data);
        $tag = '编辑';
      } else {
        unset($data['id']);
        $data['create_time'] = time();
        $data['uid'] = $this->uid;
        $data['username'] = $this->username;
        $data['_id'] = createId('ET');
        $status = Db::connect('mongodb')->name('email_tpl_list')->insert($data);
        $tag = '新增';
      }
      if ($status > 0) {
        return json(['code' => 200, 'data' => '', 'msg' => $tag . '成功']);
      } else {
        return json(['code' => -1, 'data' => '', 'msg' => $tag . '失败，请重试']);
      }
    } else {
      $id = input('param.id', '', 'trim');
      if (!$id) {
        return json(['code' => 200, 'data' => [], 'msg' => 'success']);
      }
      $data = Db::connect('mongodb')->name('email_tpl_list')->where('_id', $id)->find();
      unset($data['smtp_password']);
      return json(['code' => 200, 'data' => $data, 'msg' => 'success']);
    }
  }
  public function del_server()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $status = Db::connect('mongodb')->name('email_server_list')->where('_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function del_server_batch()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.ids/a', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $status = Db::connect('mongodb')->name('email_server_list')->whereIn('_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function test_server()
  {
    $rule = [
      'id'  => 'require',
      'email'  => 'require|email',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
      'email' => input('param.email', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $hasSetting = UserSetting::find();
    if (empty($hasSetting)) {
      return Result::Error('请先设置开发KEY');
    }
    $postD['email'] = $data['email'];
    $postD['es_id'] = $data['id'];
    $postD['dev_key'] = $hasSetting['dev_key'];
    $postD['content'] = '邮件测试';
    $postD['title'] = '邮件测试';
    $result = doSendEmail($postD);
    return Result::Success([], $result['msg']);
  }
  public function del_tpl()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $status = Db::connect('mongodb')->name('email_tpl_list')->where('_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function del_tpl_cate()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $hasTpl = Db::connect('mongodb')->name('email_tpl_list')->where('cate_id', $data['id'])->find();
    if (!empty($hasTpl)) {
      return Result::Error('该分类下存在邮件模板，不允许删除');
    }
    $status = Db::connect('mongodb')->name('email_tpl_cate')->where('_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function del_email_log()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $status = Db::connect('mongodb')->name('send_email_log')->where('_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function del_email_log_batch()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.ids/a', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $status = Db::connect('mongodb')->name('send_email_log')->whereIn('_id', $data['id'])->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function resend_email_batch()
  {
    $rule = [
      'id'  => 'require',
    ];
    $data = [
      'id' => input('param.ids/a', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $list = Db::connect('mongodb')->name('send_email_log')->whereIn('_id', $data['id'])->select();
    $resultSend = [];
    $http = new \Yurun\Util\HttpRequest;
    foreach ($list as $key => $vo) {
      $logSms = json_decode($vo['params'], true);
      $logSms['esl_id'] = $vo['_id'];
      $resultSend[] = doSendEmail($logSms, $http);
    }
    return Result::Success($resultSend, '任务提交成功，请稍后通过【邮件记录】查看发送结果');
  }
  public function send_email()
  {
    $rule = [
      'es_id|邮件服务器'  => 'require',
      'email|邮件地址'  => 'require',
      'content|邮件内容'  => 'require',
    ];
    $data = [
      'es_id' => input('param.es_id', '', 'trim'),
      'et_id' => input('param.et_id', '', 'trim'),
      'email' => input('param.email', '', 'trim'),
      'title' => input('param.title', '', 'trim'),
      'is_filter_bool' => input('param.is_filter_bool', '', 'trim'),
      'filter_id' => input('param.filter_id', '', 'trim'),
      'content' => input('param.content', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    if ($data['is_filter_bool'] == true) {
      $data['is_filter'] = 1;
    }
    $data['email'] = implode(',', explode("\n", $data['email']));
    doSendEmail($data);
    return Result::Success($data, '任务已提交，请稍后在日志中查看');
  }
  public function all_data()
  {
    $return['date'] = date('Y-m-d H:i:s', strtotime(date('Y-m-d')) - 1);
    $rule = [
      'date_num'  => 'require',
      'date_range'  => 'require',
    ];
    $data = [
      'date_num' => input('param.date_num', '', 'trim'),
      'date_range' => input('param.date_range_format/a', '', 'trim'),
      'es_id' => input('param.es_id', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }
    $whereTj['uid'] = $this->uid;
    if (!empty($data['es_id'])) {
      $whereTj['es_id'] = $data['es_id'];
    }
    $start_date = strtotime($data['date_range'][0]);
    $end_date = strtotime($data['date_range'][1]);

    if ($end_date == $start_date) {
      $cycle_type = 'hour';
      $cycle_num = 24;
    } else {
      $cycle_type = 'day';
      $cycle_num = ($end_date - $start_date) / 86400 + 1;
    }
    $end_date = $end_date + 86399;
    if ($end_date - $start_date > 86400 * 90) {
      return Result::Error('时间跨度不能大于90天');
    }
    $groupField = $cycle_type == 'hour' ? 'only_hour' : 'date';
    $whereTj['send_time'] = ['$gte' => $start_date, '$lte' => $end_date];
    $hasData = mongodb()->selectCollection('send_email_log_' . $this->uid)->aggregate([
      ['$match' => $whereTj],
      ['$group' => [
        '_id' => '$' . $groupField,
        'sv_sum' => ['$sum' => 1],
        'ssv_sum' => ['$sum' => ['$cond' => [
          'if' => ['$eq' => ['$send_result', true]],
          'then' => 1,
          'else' => 0
        ]]],
        'sfv_sum' => ['$sum' => ['$cond' => [
          'if' => ['$eq' => ['$send_result', false]],
          'then' => 1,
          'else' => 0
        ]]],
        'rv_sum' => ['$sum' => '$is_read']
      ]]
    ]);
    $newData = [];
    foreach ($hasData as $document) {
      $newData[] = (array)$document;
    }
    $fieldCount = [];
    $return['total']['rv'] = 0;
    $return['total']['sv'] = 0;
    $return['total']['sfv'] = 0;
    $return['total']['ssv'] = 0;
    foreach ($newData as $key => $vo) {
      $fieldCount[$vo['_id']] = $vo;
      $return['total']['sfv'] += $vo['sfv_sum'];
      $return['total']['ssv'] += $vo['ssv_sum'];
      $return['total']['rv'] += $vo['rv_sum'];
      $return['total']['sv'] += $vo['sv_sum'];
    }
    $chartData = [];
    $num_type = !empty($data['es_id']) ? '数' : '总数';
    for ($i = 0; $i < $cycle_num; $i++) {
      if ($cycle_type == 'hour') {
        $nowTime = $start_date + $i * 3600;
        $charItem['date'] = date('H', $nowTime) . ':00';
        $charItem['value'] = isset($fieldCount[$charItem['date']]['sv_sum']) ? $fieldCount[$charItem['date']]['sv_sum'] : 0;
        $charItem['category'] = '邮件发送' . $num_type;
        $chartData[] = $charItem;
        $charItem['value'] = isset($fieldCount[$charItem['date']]['ssv_sum']) ? $fieldCount[$charItem['date']]['ssv_sum'] : 0;
        $charItem['category'] = '发送成功' . $num_type;
        $chartData[] = $charItem;
        $charItem['value'] = isset($fieldCount[$charItem['date']]['rv_sum']) ? $fieldCount[$charItem['date']]['rv_sum'] : 0;
        $charItem['category'] = '邮件阅读' . $num_type;
        $chartData[] = $charItem;
      } else {
        $nowTime = $start_date + $i * 86400;
        $charItem['date'] = date('Y-m-d', $nowTime);
        $charItem['value'] = isset($fieldCount[date('Ymd', $nowTime)]['sv_sum']) ? $fieldCount[date('Ymd', $nowTime)]['sv_sum'] : 0;
        $charItem['category'] = '邮件发送' . $num_type;
        $chartData[] = $charItem;
        $charItem['value'] = isset($fieldCount[date('Ymd', $nowTime)]['ssv_sum']) ? $fieldCount[date('Ymd', $nowTime)]['ssv_sum'] : 0;
        $charItem['category'] = '发送成功' . $num_type;
        $chartData[] = $charItem;
        $charItem['value'] = isset($fieldCount[date('Ymd', $nowTime)]['rv_sum']) ? $fieldCount[date('Ymd', $nowTime)]['rv_sum'] : 0;
        $charItem['category'] = '邮件阅读' . $num_type;
        $chartData[] = $charItem;
      }
    }
    if ($cycle_type == 'day') {
      $charItem['date'] = date('Y-m-d', $end_date);
      $charItem['value'] = isset($fieldCount[date('Ymd', $nowTime)]['sv_sum']) ? $fieldCount[date('Ymd', $nowTime)]['sv_sum'] : 0;
      $charItem['category'] = '邮件发送' . $num_type;
      $chartData[] = $charItem;
      $charItem['value'] = isset($fieldCount[date('Ymd', $nowTime)]['ssv_sum']) ? $fieldCount[date('Ymd', $nowTime)]['ssv_sum'] : 0;
      $charItem['category'] = '发送成功' . $num_type;
      $chartData[] = $charItem;
      $charItem['value'] = isset($fieldCount[date('Ymd', $nowTime)]['rv_sum']) ? $fieldCount[date('Ymd', $nowTime)]['rv_sum'] : 0;
      $charItem['category'] = '邮件阅读' . $num_type;
      $chartData[] = $charItem;
    }
    $return['total']['rv_sv_rate'] = ($return['total']['sv'] > 0)?round($return['total']['rv'] / $return['total']['sv'] * 100, 2):0;
    $return['total']['ssv_sv_rate'] = ($return['total']['sv'] > 0)?round($return['total']['ssv'] / $return['total']['sv'] * 100, 2):0;
    $return['chart'] = $chartData;
    return Result::Success($return);
  }
  public function all_email_data()
  {
    $rule = [
      'date_num'  => 'require',
      'date_range'  => 'require',
    ];
    $data = [
      'date_num' => input('param.date_num', '', 'trim'),
      'from_type' => input('param.from_type', '', 'trim'),
      'date_range' => input('param.date_range_format/a', '', 'trim'),
      'es_id' => input('param.es_id', '', 'trim'),
      'email' => input('param.email', '', 'trim'),
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'pageSize' => input('param.pageSize', 15, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }

    $start_date = strtotime($data['date_range'][0]);
    $end_date = strtotime($data['date_range'][1]);

    $end_date = $end_date + 86399;
    if ($end_date - $start_date > 86400 * 90) {
      return Result::Error('时间跨度不能大于90天');
    }
    $where['hour_stamp'] = ['$gte' => $start_date, '$lte' => $end_date];
    $skip = ($data['pageNo'] - 1) * $data['pageSize'];

    $where['uid'] = $this->uid;
    $where['send_result'] = true;
    if (!empty($data['es_id'])) {
      $where['es_id'] = $data['es_id'];
    }
    $whereTj[] = ['uid', '=', $this->uid];
    $whereTj[] = ['send_result', '=', true];
    if (!empty($data['es_id'])) {
      $whereTj[] = ['es_id', '=', $data['es_id']];
    }
    $whereTj[] = ['hour_stamp', 'between', [$start_date, $end_date]];
    $fromType = '$email';
    $hasAds = mongodb()->selectCollection('send_email_log_' . $this->uid)->aggregate([
      ['$match' => $where],
      ['$group' => ['_id' => $fromType, 'count' => ['$sum' => 1]]],
      ['$sort' => ['count' => -1]],
      ['$skip' => (int)$skip],
      ['$limit' => (int)$data['pageSize']],
    ]);
    $newData = [];
    foreach ($hasAds as $document) {
      $newData[] = (array)$document;
    }
    $totalNum = Db::connect('mongodb')->name('send_email_log')->where($whereTj)->count();
    $totalNum = empty($totalNum)?0:(int)$totalNum;
    foreach ($newData as $key => $vo) {
      $newData[$key]['rate'] = round($vo['count'] / $totalNum * 100, 2) . '%';
    }
    $returnData['data'] = $newData;
    $returnData['totalCount'] = $totalNum;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
  public function del_log_all()
  {
    $rule = [
      'type|清空类型'  => 'require',
    ];
    $data = [
      'es_id' => input('param.es_id', '', 'trim'),
      'type' => input('param.type', '', 'trim'),
      'send_time_ranges' => input('param.send_time_ranges/a', '', 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $where['uid'] = $this->uid;
    if (!empty($data['es_id'])) {
      $where['es_id'] = trim($data['es_id']);
    }
    if ($data['type'] == 'all') {
      $status = Db::connect('mongodb')->name('send_email_log')->where($where)->delete();
    } else {
      $start_time = strtotime($data['send_time_ranges'][0]);
      $end_time = strtotime($data['send_time_ranges'][1]);
      if ($end_time - $start_time > 86400 * 90) {
        return Result::Error('时间跨度不能大于90天');
      }
      $status = Db::connect('mongodb')->name('send_email_log')->where($where)->whereBetweenTime('create_time', $start_time, $end_time)->delete();
    }
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function del_log_fail()
  {
    $data = [
      'es_id' => input('param.es_id', '', 'trim'),
    ];
    $where['uid'] = $this->uid;
    $where['send_result'] = false;
    if (!empty($data['es_id'])) {
      $where['es_id'] = trim($data['es_id']);
    }
    $status = Db::connect('mongodb')->name('send_email_log_' . $this->uid)->where($where)->delete();
    if ($status > 0) {
      return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
    } else {
      return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请稍后重试']);
    }
  }
  public function single_email_data()
  {
    $rule = [
      'date_num'  => 'require',
      'date_range'  => 'require',
    ];
    $data = [
      'date_num' => input('param.date_num', '', 'trim'),
      'from_type' => input('param.from_type', '', 'trim'),
      'date_range' => input('param.date_range_format/a', '', 'trim'),
      'es_id' => input('param.es_id', '', 'trim'),
      'email' => input('param.email', '', 'trim'),
      'email_tab' => input('param.email_tab', '', 'trim'),
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'pageSize' => input('param.pageSize', 200, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return Result::Error($validate->getError());
    }

    $start_date = strtotime($data['date_range'][0]);
    $end_date = strtotime($data['date_range'][1]);

    $end_date = $end_date + 86399;
    if ($end_date - $start_date > 86400 * 90) {
      return Result::Error('时间跨度不能大于90天');
    }
    $where['hour_stamp'] = ['$gte' => $start_date, '$lte' => $end_date];
    $skip = ($data['pageNo'] - 1) * $data['pageSize'];

    $where['uid'] = $this->uid;
    $where['send_result'] = true;
    if (!empty($data['es_id'])) {
      $where['es_id'] = $data['es_id'];
    }
    if (!empty($data['email'])) {
      $where['email'] = $data['email'];
    }
    $whereTj[] = ['uid', '=', $this->uid];
    $whereTj[] = ['send_result', '=', true];
    if (!empty($data['email'])) {
      $whereTj[] = ['email', '=', $data['email']];
    }
    $whereTj[] = ['hour_stamp', 'between', [$start_date, $end_date]];
    switch ($data['email_tab']) {
      case '1':
        $fromType = '$es_id';
        break;
      case '2':
        $fromType = '$title';
        if (!empty($data['es_id'])) {
          $whereTj[] = ['es_id', '=', $data['es_id']];
        }
        break;
      case '3':
        $fromType = '$title';
        if (!empty($data['es_id'])) {
          $whereTj[] = ['es_id', '=', $data['es_id']];
        }
        break;
      default:
        $fromType = '$email';
        break;
    }
    if ($data['email_tab'] == '3') {
      $where['is_read'] = 1;
      $read_count = mongodb()->selectCollection('send_email_log_' . $this->uid)->count($where);
      $where['is_read'] = 0;
      $unread_count = mongodb()->selectCollection('send_email_log_' . $this->uid)->count($where);
      $newData = [];
      $itemBuild['_id'] = '已读量';
      $itemBuild['count'] = $read_count;
      $newData[] = $itemBuild;
      $itemBuild['_id'] = '未读量';
      $itemBuild['count'] = $unread_count;
      $newData[] = $itemBuild;
    } else {
      $hasAds = mongodb()->selectCollection('send_email_log_' . $this->uid)->aggregate([
        ['$match' => $where],
        ['$group' => ['_id' => $fromType, 'count' => ['$sum' => 1]]],
        ['$sort' => ['count' => -1]],
        ['$skip' => (int)$skip],
        ['$limit' => (int)$data['pageSize']],
      ]);
      $newData = [];
      foreach ($hasAds as $document) {
        $newData[] = (array)$document;
      }
    }

    $totalNum = Db::connect('mongodb')->name('send_email_log')->where($whereTj)->count();
    foreach ($newData as $key => $vo) {
      $newData[$key]['rate'] = ($totalNum == 0) ? 0 : round($vo['count'] / $totalNum * 100, 2) . '%';
    }
    $returnData['data'] = $newData;
    // $returnData['totalCount'] = $totalNum;
    $returnData['pageNo'] = (int) $data['pageNo'];
    $returnData['pageSize'] = (int) $data['pageSize'];
    return Result::Success($returnData);
  }
}
